package com.cbgolf.oa.activity.result;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import com.cbgolf.oa.R;
import com.cbgolf.oa.adapter.MyBaseAdapter;
import com.cbgolf.oa.base.BaseActivity;
import com.cbgolf.oa.entity.CodeTypeBean;
import com.cbgolf.oa.entity.GroupInfoBean;
import com.cbgolf.oa.entity.TeeTimeBean;
import com.cbgolf.oa.net.NetCallBack;
import com.cbgolf.oa.net.NetUtils;
import com.cbgolf.oa.net.Web;
import com.cbgolf.oa.net.WebAPI;
import com.cbgolf.oa.user.UserData;
import com.cbgolf.oa.util.AnimaUtil;
import com.cbgolf.oa.util.DataUtil;
import com.cbgolf.oa.util.DateUtil;
import com.cbgolf.oa.util.DialogUtil;
import com.cbgolf.oa.util.PopUtil;
import com.cbgolf.oa.util.TextUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.widget.CycleWheelView;
import com.cbgolf.oa.widget.ListViewNew;
import com.cbgolf.oa.widget.autolayout.utils.AutoUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

/**
 * Created by lq on 2017/8/31.
 */

public class ScoreCardActivity extends BaseActivity {

  //top
  @ViewInject(R.id.topBack_ll)
  private View topBack;
  @ViewInject(R.id.title_tv)
  private TextView topTitle;
  @ViewInject(R.id.topRight_iv)
  private ImageView topRightIv;
  //body
  @ViewInject(R.id.a_score_card_time_view)
  private View timeView;
  @ViewInject(R.id.a_score_card_time_tv)
  private TextView timeTv;
  @ViewInject(R.id.a_score_card_mem_choose_tv)
  private TextView memChooseTv;
  @ViewInject(R.id.a_score_listview)
  private ListViewNew listView;

  @ViewInject(R.id.a_score_submit_tv)
  private TextView subMitTv;

  //var


  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.a_score_card);
  }

  @Override
  protected void findViews() {
    x.view().inject(this);
  }

  @Override
  protected void setViews() {
    topTitle.setText("记分卡");
    topRightIv.setVisibility(View.VISIBLE);
    topRightIv.setImageResource(R.drawable.jilu);

  }

  @Override
  protected void setListener() {
    topBack.setOnClickListener(v -> finish());
    topRightIv.setOnClickListener(v -> mStartActivity(ScoreHistoryActivity.class));
    timeView.setOnClickListener(v -> {
      if (listA_Z.size() == 0) {
        Util.show("暂无半场信息");
        return;
      }
      showTimeDialog();

    });
    memChooseTv.setOnClickListener(v -> {
      if (listView.getVisibility() == View.VISIBLE) {
        listView.setVisibility(View.GONE);
        return;
      }
      if (Util.isNull(teeTimeId)) {
        Util.show("请选择击球时间");
        return;
      }
      listView.setVisibility(View.VISIBLE);
    });
    subMitTv.setOnClickListener(v -> checkInfo());


  }

  private void checkInfo() {

    if (null == mapPhones || mapPhones.isEmpty()) {
      Util.show("请选择组员");
      return;
    }
    showSubmitTipDialog();


  }

  private void showSubmitTipDialog() {
    String title = "温馨提示";
    String msg = "您是否确认开启记分，一旦选择则不可修改。";
    DialogUtil.showMsgDialog(context, title, msg, () -> openScoreWrite());
  }

  private void openScoreWrite() {
    if (!Util.isNetWorkConnected()) {
      Util.showNoNet();
      return;
    }
    final ArrayList<String> listPhones = new ArrayList<>();
    org.json.JSONArray array = new org.json.JSONArray();
    for (Map.Entry<Integer, String> me : mapPhones.entrySet()) {
      listPhones.add(me.getValue());
      array.put(me.getValue());
    }
    String url = WebAPI.record_groupinfo_put;
    Map<String, Object> map = new HashMap<>();
    JSONObject json = new JSONObject();
    try {
      json.put("phones", array);
      json.put("groupId", groupId);
    } catch (JSONException e) {
      e.printStackTrace();
    }
    map.put("token", null == UserData.getUser() ? "" : UserData.getUser().getToken());
    map.put("data", json);
    AnimaUtil.showLoading(context);
    Web.postJsonOk(url, map, new NetCallBack(response -> {
      AnimaUtil.stopLoading();
      if (NetUtils.SUCCESS != response.statusCode) {
        Util.showNetError();
        return;
      }
      Intent intent = new Intent(context, ScoreWriteActivity.class);
      intent.putExtra("groupId", groupId);
      intent.putStringArrayListExtra("phones", listPhones);
      startActivity(intent);
    }));
  }

  @Override
  protected void loadData() {
    super.loadData();
    selectParkA2Z();
  }

  private List<CodeTypeBean> listA_Z = new ArrayList<>();
  private List<String> listNameA_Z = new ArrayList<>();

  private void selectParkA2Z() {
    String url = WebAPI.park_coures_select_get;
    Web.getOK(url, new NetCallBack(response -> {
      if (NetUtils.SUCCESS != response.statusCode) {
        Util.showNetError();
        return;
      }
      listA_Z = DataUtil.getList(response.result, CodeTypeBean.class);
      if (!Util.listIsNull(listA_Z)) {
        banChangType = listA_Z.get(0).codeType;
        selectTeeTime();
      }
    }));
  }

  List<TeeTimeBean> listTeeTime = new ArrayList<>();
  private String banChangType;

  private void selectTeeTime() {
    listTeeTime.clear();
    listHour.clear();
    listMinute.clear();
    listTimes.clear();
    if (null != pvHour) {
      pvHour.clear();
    }
    if (null != pvMinute) {
      pvMinute.clear();
    }
    String url = WebAPI.teetime_select_get;
    Map<String, String> map = new HashMap<>(1);
    map.put("codeType", banChangType);
    Web.getOK(url, map, new NetCallBack(response -> {
      if (NetUtils.SUCCESS != response.statusCode) {
        Util.showNetError();
        return;
      }
      if (Util.isNull(response.result)) {
        return;
      }
      List<TeeTimeBean> list = DataUtil.getList(response.result, TeeTimeBean.class);
      if (!Util.listIsNull(list)) {
        listTeeTime.addAll(list);
        if (null != mDialog && mDialog.isShowing()) {
          setWheel(pvHour, HOUR);
          setWheel(pvMinute, MINUTE);
        }
      }
    }));
  }

  CycleWheelView pvHour;
  CycleWheelView pvMinute;
  private String hourSelected;
  private String minuteSelected;

  private Dialog mDialog;

  private void showTimeDialog() {
    mDialog = new Dialog(context, R.style.mDialog);
    View view = getLayoutInflater().inflate(R.layout.dialog_teetiem, null);
    TextView cancelTv = (TextView) view.findViewById(R.id.dialog_cancel_tv);
    TextView subMitTv = (TextView) view.findViewById(R.id.dialog_submit_tv);
    final View abView = view.findViewById(R.id.dialog_ab_ll);
    final TextView abTv = (TextView) view.findViewById(R.id.dialog_ab_tv);
    pvHour = (CycleWheelView) view.findViewById(R.id.cwv_hour);
    pvMinute = (CycleWheelView) view.findViewById(R.id.cwv_minute);
    setWheel(pvHour, HOUR);
    setWheel(pvMinute, MINUTE);

    if (listA_Z.size() > 0) {
      if (!Util.isNull(banChangType)) {
        abTv.setText(banChangType.substring(0, 1));
      } else {
        String A = listA_Z.get(0).codeType;
        if (!Util.isNull(A)) {
          abTv.setText(A.substring(0, 1));
        }
        if (listTeeTime.size() > 0) {
          teeTimeId = listTeeTime.get(0).teeTimeId;
        }
      }
    }

    AutoUtil.auto(view);
    mDialog.setContentView(view);
    abView.setOnClickListener(v -> {
      listNameA_Z.clear();
      for (int i = 0; i < listA_Z.size(); i++) {
        if (!Util.isNull(listA_Z.get(i).codeType)) {
          listNameA_Z.add(listA_Z.get(i).codeType.substring(0, 1));
        }
      }
      PopUtil.setStringData(listNameA_Z);
      int width = abView.getMeasuredWidth();
      PopUtil.setPopWidthAndHeight(width, 0);
      PopUtil.showList(context, abView, position -> {
        banChangType = listA_Z.get(position).codeType;
        if (!Util.isNull(banChangType)) {
          abTv.setText(banChangType.substring(0, 1));
        }
        selectTeeTime();
      });
    });
    cancelTv.setOnClickListener(v -> {
      mDialog.cancel();
      mDialog.dismiss();
      reSetData();
    });
    subMitTv.setOnClickListener(v -> {
      mDialog.cancel();
      mDialog.dismiss();
      if (Util.isNull(teeTimeId)) {
        return;
      }
      if (null != adapter) {
        adapter.clear();
        adapter.updateUI();
      }
      timeTv.setText(TextUtil.Text(initTime));
      selectGroupInfo();
      reSetData();

    });
    mDialog.show();
  }

  private void reSetData() {
    pvHour = null;
    pvMinute = null;
    listTimes.clear();
    teeTimeId = null;
  }

  private final int HOUR = 1;
  private final int MINUTE = 2;
  List<String> listHour = new ArrayList<>();
  List<String> listMinute = new ArrayList<>();
  List<String> listTimes = new ArrayList<>();

  private void setWheel(CycleWheelView pv, int type) {
    if (null == pv) {
      return;
    }
    String hour;
    String minute;
    String timeStr;
    listHour.clear();
    listMinute.clear();
    if (!Util.listIsNull(listTeeTime)) {
      for (int i = 0; i < listTeeTime.size(); i++) {
        hour = DateUtil.stampToDate(String.valueOf(listTeeTime.get(i).teeTimeDate), "HH");
        minute = DateUtil.stampToDate(String.valueOf(listTeeTime.get(i).teeTimeDate), "mm");
        timeStr = DateUtil.stampToDate(listTeeTime.get(i).teeTimeDate, DateUtil.formatYMDHm);
        if (!Util.isNull(timeStr) && !listTimes.contains(timeStr)) {
          listTimes.add(timeStr);
        }
        if (!Util.isNull(hour) && !listHour.contains(hour)) {
          listHour.add(hour);
        }
        if (!Util.isNull(minute) && !listMinute.contains(minute)) {
          listMinute.add(minute);
        }
      }
    }
    if (Util.listIsNull(listHour)) {
      listHour.add("");
    }
    if (Util.listIsNull(listMinute)) {
      listMinute.add("");
    }
    switch (type) {
      case HOUR:
        pv.setLabels(listHour);
        if (listHour.contains(hourSelected)) {
          pv.setSelection(listHour.indexOf(hourSelected));
        } else {
          pv.setSelection(0);
          hourSelected = listHour.get(0);
        }
        break;
      case MINUTE:
        pv.setLabels(listMinute);
        if (listMinute.contains(minuteSelected)) {
          pv.setSelection(listMinute.indexOf(minuteSelected));
        } else {
          pv.setSelection(0);
          minuteSelected = listHour.get(0);
        }
        break;
      default:
        break;
    }
    pv.setCycleEnable(false);
    try {
      pv.setWheelSize(3);
    } catch (CycleWheelView.CycleWheelViewException e) {
      e.printStackTrace();
    }
    pv.setAlphaGradual(0.5f);
    pv.setDivider(Color.parseColor("#d7d7d7"), 2);
    pv.setSolid(Color.TRANSPARENT, Color.WHITE);
    pv.setLabelColor(ContextCompat.getColor(context, R.color.text_gray));
    pv.setLabelSelectColor(ContextCompat.getColor(context, R.color.bg_blue));
    if (!Util.listIsNull(listTeeTime)) {
      initTime = DateUtil.stampToDate(String.valueOf(listTeeTime.get(0).teeTimeDate),
          DateUtil.formatYMD)
          + " " + hourSelected + ":" + minuteSelected;
      try {
        if (listTimes.contains(initTime)) {
          teeTimeId = listTeeTime.get(listTimes.indexOf(initTime)).teeTimeId;
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      pvHour.setOnWheelItemSelectedListener((position, label) -> {
        hourSelected = label;
        initTime = DateUtil.stampToDate(String.valueOf(listTeeTime.get(0).teeTimeDate),
            DateUtil.formatYMD)
            + " " + hourSelected + ":" + minuteSelected;
        try {
          if (listTimes.contains(initTime)) {
            teeTimeId = listTeeTime.get(listTimes.indexOf(initTime)).teeTimeId;
          }
        } catch (Exception e) {
        }
      });
      pvMinute.setOnWheelItemSelectedListener((position, label) -> {
        minuteSelected = label;
        initTime = DateUtil
            .stampToDate(String.valueOf(listTeeTime.get(0).teeTimeDate), DateUtil.formatYMD)
            + " " + hourSelected + ":" + minuteSelected;
        try {
          if (listTimes.contains(initTime)) {
            teeTimeId = listTeeTime.get(listTimes.indexOf(initTime)).teeTimeId;
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      });
    }

  }

  private String initTime;
  private String teeTimeId;
  private String groupId;
  MyBaseAdapter<GroupInfoBean> adapter;

  private void selectGroupInfo() {
    AnimaUtil.showLoading(context);
    Web.getOK(WebAPI.teetime_groupinfo_select_get + "/" + teeTimeId,
        new NetCallBack(response -> {
          AnimaUtil.stopLoading();
          if (NetUtils.SUCCESS != response.statusCode) {
            Util.showNetError();
            return;
          }
          List<GroupInfoBean> list = DataUtil.getList(response.result, GroupInfoBean.class);
          if (Util.listIsNull(list)) {
            Util.show("暂无组员信息");
            return;
          }
          listView.setVisibility(View.VISIBLE);
          mapPhones.clear();
          adapter = new MyBaseAdapter<GroupInfoBean>(R.layout.item_group, context, list) {
            @Override
            public View getView(final int position, View view, ViewGroup parent,
                GroupInfoBean m_groupInfo) {
              setText(R.id.item_group_num_tv, m_groupInfo.consumerCard);
              setText(R.id.item_group_name_tv, m_groupInfo.name);
              setText(R.id.item_group_vip_tv, m_groupInfo.identityName);
              final CheckBox cb = (CheckBox) view.findViewById(R.id.item_group_checkbox);
              View item = view.findViewById(R.id.item_group_layout_ll);
              if (m_groupInfo.selected) {
                cb.setChecked(true);
                item.setEnabled(false);
              } else {
                cb.setChecked(false);
                item.setEnabled(true);
              }
              final String phone = m_groupInfo.phone;
              item.setOnClickListener(v -> {
                cb.toggle();
                if (cb.isChecked()) {
                  mapPhones.put(position, phone);
                  if (View.GONE == subMitTv.getVisibility()) {
                    subMitTv.setVisibility(View.VISIBLE);
                  }
                } else {
                  if (mapPhones.containsKey(position)) {
                    mapPhones.remove(position);
                  }
                }
              });
              return view;
            }
          };
          listView.setAdapter(adapter);
          groupId = list.get(0).groupId;
        }));
  }

  private Map<Integer, String> mapPhones = new HashMap<>(4);
}
